import { Client } from "api/client/Client";
import { GuildDto } from "./dto/Guild";
import { Snowflake } from "./utils/Snowflake";
import { GuildChannel } from "./GuildChannel"
import { Role } from "../structures/Role"
import { GuildMember } from "./GuildMember";
export class Guild {
    id!: Snowflake
    name!: string
    icon?: string
    splash?: string
    channels: Record<string, GuildChannel> = {};
    roles: Record<string, Role> = {};
    members: Record<string, GuildMember> = {};
    membersList: string[] = [];

    constructor(private client: Client, data: GuildDto) {
        this._patch(data);
    }

    get iconURL() {
        return this.icon && `https://cdn.discordapp.com/icons/${this.id}/${this.icon}.png`
    }

    get position() {
        if (!this.client?.user || !this.id) {
          return null;
        }
      
        if (!this.client.userSettings?.guildPositions) {
          return null;
        }
      
        return this.client.userSettings.guildPositions.indexOf(this.id);
    }

    private _patch(data: GuildDto) {

        // console.log("Guild " + JSON.stringify(data))

        this.id = data.id;
        this.name = data.name;
        
        if("icon" in data) {
            this.icon = data.icon ?? undefined;
        }

        if("splash" in data) {
            this.splash = data.splash ?? undefined;
        }

        if("roles" in data) {
            data.roles.forEach(role=>{
                this.roles[role.id] = new Role(this.client, role)
            })
        }
        
        if("members" in data) {
            data.members.forEach(member=>{
                
                if (!this.members[member.user.id]) {
                    this.membersList.push(member.user.id)
        
                    this.members[member.user.id] = new GuildMember(this.client, this, member)
                } else {
                    this.members[member.user.id]._patch(member)
                }
            })
        }

        if("channels" in data) {
            data.channels.forEach(channel=>{
                this.channels[channel.id] = new GuildChannel(this.client, this, channel)
                this.client.guildChannels[channel.id] = this.channels[channel.id];
            })
        }
    }
}